package com.ist.word.logic;

import java.util.HashMap;
import java.util.Random;

import com.ist.word.dao.WordDAO;
import com.ist.word.model.Word;

public class WordGameLogic {
	
	/**
	 * 随机取单词的个数
	 */
	private final int WORD_QUANTITY = 10;

	/**
	 * 数据库访问类
	 */
	private WordDAO wordDAO;

	/**
	 * 存储当前正在游戏的那个单词
	 */
	private Word randomWord;
	
	/**
	 * 存储当前所有用于游戏的单词的集合
	 */
	private HashMap<Integer, Word> wordMap = new HashMap<Integer, Word>();

	/**
	 * 游戏总分
	 */
	private int totalScore;

	public WordGameLogic() {
		wordDAO = new WordDAO();
	}

	/**
	 * 根据传入单词进行拆分，返回乱序后的单词字符数组
     * 乱序：随机一个字符长度内的整数，作为与第i个元素交换的索引，以实现在字符串的乱序
	 * 
	 * @param Word
	 * @return char[]
	 */
	public char[] splitWord(Word word) {
		char[] letters = word.getWords().toCharArray();
		Random rand = new Random();
		int length = letters.length, k = 0;
		for (int i = 0; i < length; i++) {
			k = rand.nextInt(length);
			char temp = letters[i];
			letters[i] = letters[k];
			letters[k] = temp;
		}
		return letters;
	}

	/**
	 * 查看所传入的单词是否存在,获取单词的翻译，等信息
	 * 
	 * @param Word
	 * @return Word
	 */
	public Word getWord(Word word) {
		Word tempWord = wordDAO.selectByWord(word);
		return tempWord;
	}

	/**
	 * 玩家第一次游戏时，随机取出一定数量个单词，存放在words[]数组和HashMap(用单词的id号作为键)里，然后供用户游戏使用(每取一个，HashMap里会减少一个)
	 * 当10个单词用完后，HashMap会置空，再进行一次随机取10个单词，如果反复
	 * 
	 * @param Word
	 * @return Word
	 * @throws Exception 
	 */
	public Word getRandomWord() {
		if (wordMap.isEmpty()) {
			Word[] words = wordDAO.selectWords(WORD_QUANTITY);
			for (Word word : words) {
				if (!wordMap.containsKey(word.getWordNo())) {
					wordMap.put(word.getWordNo(), word);
				}
			}
		}
		for (Integer i : wordMap.keySet()) {
			randomWord = wordMap.get(i);
			wordMap.remove(i);
			break;
		}
		return randomWord;
	}

	/**
	 * 分数统计，10分制
	 * 
	 * @param Word
	 * @return Integer
	 */
	public int scoreStatistics(Word word) {
		int score=0;
		if (word != null) {
			int userSize = word.getWords().length();
			int currSize = randomWord.getWords().length();
			score = (int) (((double) userSize / (double) currSize) * 10);
			//totalScore += score;//modified by datong, no accumulate.
		}
		return score;
	}
	
	/**
	 * 单个单词得到的分数，10分制
	 * 
	 * @param Word
	 * @return Integer
	 */
	public int getWordScore(Word word) {
		int score=0;
		if (word != null) {
			int userSize = word.getWords().length();
			int currSize = randomWord.getWords().length();
			score = (int) (((double) userSize / (double) currSize) * 10);
		}
		return score;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println(new WordGameLogic().getRandomWord().getWords());
	}

}
